def encode(s):
    if s == '':
        return ('', -1)
    matrix = sorted([s[-i:]+s[0:-i] for i in range(len(s))])
    return (''.join(x[-1] for x in matrix), matrix.index(s)) if s else ''


def decode(s, n):
    if s == '':
        return ''
    matrix = sorted(list(s))
    for j in range(len(s)-1):
        matrix = sorted([s[i]+v for i, v in enumerate(matrix)])
    return matrix[n]
